package org.wishwork.api.stock.other.query;

import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.wishwork.api.Api;
import org.wishwork.api.stock.other.query.response.OtherInOutQueryResponse;
import org.wishwork.context.Context;
import org.wishwork.helper.HttpHelper;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @description: 其它出入库查询
 * @author: WangYX
 * @create: 2022-04-12 14:02
 * @Version: 1.0.0
 **/

public class OtherInOutQueryApi extends Api<List<OtherInOutQueryResponse>, OtherInOutQueryRequest> {

    private static final Logger log = LoggerFactory.getLogger(OtherInOutQueryApi.class);

    private Context context;

    public OtherInOutQueryApi(Context context) {
        this.context = context;
    }

    @Override
    protected String query(OtherInOutQueryRequest otherInOutQueryRequest) throws Exception {
        String url = "/open/other/inout/query";
        Map<String, Object> params = new HashMap<>();
        if (otherInOutQueryRequest.getSoIds() != null && otherInOutQueryRequest.getSoIds().size() > 0) {
            params.put("so_ids", otherInOutQueryRequest.getSoIds());
        }
        if (otherInOutQueryRequest.getTypes() != null && otherInOutQueryRequest.getTypes().size() > 0) {
            params.put("types", otherInOutQueryRequest.getTypes());
        }
        if (StrUtil.isNotEmpty(otherInOutQueryRequest.getStatus())) {
            params.put("status", otherInOutQueryRequest.getStatus());
        }
        if (otherInOutQueryRequest.getWmsCoId() != null) {
            params.put("wms_co_id", otherInOutQueryRequest.getWmsCoId());
        }
        return HttpHelper.sendRequest(otherInOutQueryRequest, params, url);
    }

    @Override
    protected List<OtherInOutQueryResponse> process(JSONObject data, OtherInOutQueryRequest otherInOutQueryRequest) throws Exception {
        JSONArray datas = data.getJSONArray("datas");
        List<OtherInOutQueryResponse> otherInOutQueryResponses = datas.toJavaList(OtherInOutQueryResponse.class);
        Boolean has_next = data.getBoolean("has_next");
        if (has_next) {
            Integer pageIndex = otherInOutQueryRequest.getPageIndex();
            OtherInOutQueryRequest build = otherInOutQueryRequest.toBuilder().pageIndex(++pageIndex).build();
            List<OtherInOutQueryResponse> business = business(build);
            otherInOutQueryResponses.addAll(business);
        }
        return otherInOutQueryResponses;
    }
}
